package io.broker.api.client.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.broker.api.client.domain.account.*;
import io.broker.api.client.domain.general.BiKiMessage;
import okhttp3.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class BrokerApiBiKiService {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .pingInterval(10, TimeUnit.SECONDS) // websocket 轮训间隔
            .build();

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private final String token;

    public BrokerApiBiKiService(String token) {
        this.token = token;
    }

    public BiKiMessage newOrder(OrderSide side, String symbol, BigDecimal quantity, BigDecimal price) throws JsonProcessingException {
        Map<String, Object> params = new HashMap<>();
        params.put("side", side.name());
        params.put("price", price);
        params.put("volume", quantity);
        params.put("symbol", symbol);
        params.put("type", 1);

        return callRequest(params);
    }

    public BiKiMessage cancelOrder(String symbol, BigDecimal orderId) throws JsonProcessingException {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        params.put("symbol", symbol);

        return callRequest(params);
    }

    private BiKiMessage callRequest(Map<String, Object> params) throws JsonProcessingException {
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        RequestBody body = RequestBody.create(mediaType, objectMapper.writeValueAsString(params));
        Request request = new Request.Builder()
                .url("https://www.biki.com/fe-ex-api/order/create")
                .post(body)
                .addHeader("exchange-token", token)
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("Accept", "*/*")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Host", "www.biki.com")
                .addHeader("Content-Length", "125")
                .addHeader("cache-control", "no-cache")
                .build();
        try (Response response = client.newCall(request).execute()) {
            String responseValue = Objects.requireNonNull(response.body()).string();
            System.out.println(responseValue);
            return objectMapper.readValue(responseValue, BiKiMessage.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Order> getOpenOrders() {

        Request request =
                new Request.Builder()
                        .url(
                                "https://www.beex.one/api/order/open_orders?c_token="
                                        + token
                                        + "&account_id=454834027336190720&from_order_id=0&limit=50")
                        .get()
                        .addHeader("Sec-Fetch-Mode", "cors")
                        .addHeader("Sec-Fetch-Site", "same-origin")
                        .addHeader("Origin", "https://www.beex.one")
                        .addHeader("Accept-Encoding", "deflate, br")
                        .addHeader("accept-language", "zh-cn")
                        .addHeader(
                                "User-Agent",
                                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36")
                        .addHeader("content-type", "application/x-www-form-urlencoded")
                        .addHeader("Accept", "*/*")
                        .addHeader("Referer", "https://www.beex.one/exchange/665/BEE/USDT")
                        .addHeader("x-requested-with", "XMLHttpRequest")
                        .addHeader("Connection", "keep-alive")
                        .addHeader("cache-control", "no-cache")
                        .build();

        try (Response response = client.newCall(request).execute()) {
            String responseValue = Objects.requireNonNull(response.body()).string();
            Order[] beeOrders = objectMapper.readValue(responseValue, Order[].class);

            return Arrays.asList(beeOrders);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
